﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GD.VehicleManage.Data;
using Microsoft.Extensions.Options;

namespace 数据库主从同步测试.Models {
    public class NewsService : INewsService {
        public ConnectionStrings connectonStrings;

        public NewsService(IOptions<ConnectionStrings> option) {
            connectonStrings = option.Value;
        }

        public News GetById(int id) {
            var db = DbHelper.NewSqlSugarClient(connectonStrings.DevConnection);
            return db.Queryable<News>().InSingle(id);
        }

        public async Task<bool> DeleteByIdAsync(int id) {
            var db = DbHelper.NewSqlSugarClient(connectonStrings.DefaultConnection);
            var r = await db.Deleteable<News>().In(id).ExecuteCommandAsync();
            return r > 0;
        }

        public async Task<IEnumerable<News>> GetNewsAsync() {
            var db = DbHelper.NewSqlSugarClient(connectonStrings.DevConnection);
            return await db.Queryable<News>().OrderBy(it => it.Id, SqlSugar.OrderByType.Desc).ToListAsync();
        }


        public async Task<int> CreateAsync(CreateNews news) {
            var db = DbHelper.NewSqlSugarClient(connectonStrings.DefaultConnection);
            return await db.Insertable(new News() {
                Content = news.Content,
                CreateTime = DateTime.Now,
                LastUpdateTime = DateTime.Now
            }).ExecuteReturnIdentityAsync();
        }
    }
}
